import configService from "@/common/service/config.service.js";
import store from "@/store/index.js";
import { ACCESS_TOKEN } from "@/common/util/constants.js";
class socket {
  constructor(options) {
    this.socketUrl = "ws://192.168.0.182:22504";
    this.socketStart = true; // 关闭socket
    this.monitorSocketError();
    this.monitorSocketClose();
    this.socketReceive();
  }
  init(socket_type, callback) {
    const _this = this;
    if (configService.apiUrl) {
      if (this.socketStart) {
        console.log("webSocket已经启动了");
      } else {
        // let userid=store.state.userid?store.state.userid:store.getters.userid;
        // let url=this.socketUrl.replace("https://","wss://").replace("http://","ws://")+"/"+socket_type+"/"+userid+"_app";
        // update-begin-author:lsq date:20230506 for:[issues/497]websocket连接打开失败
        // let token = uni.getStorageSync('Access-Token')

        let url = this.socketUrl
          .replace("https://", "wss://")
          .replace("http://", "ws://");
        console.log("启动this.socketUrl连接地址:", url);
        uni.connectSocket({
          url: url,
          success(res) {
            console.log("websocket连接成功11", res);
            uni.onSocketOpen((res) => {
              console.log("onSocketOpen", res);
              const _this = this;
              _this.socketReceive(); // 在这里调用socketReceive方法
              _this.socketStart = true;
              _this.send(); // 在这里调用sendSocketMessage方法
              callback && callback();
              console.log("WebSocket连接已打开！");
            });
          },
          fail(err) {
            console.log("websocket连接失败", err);
          },
          // method: 'GET',
          // protocols:[token]
        });
        // update-end-author:lsq date:20230506 for:[issues/497]websocket连接打开失败

        // uni.onSocketOpen((res) => {
        // 	console.log('onSocketOpen','onSocketOpen');
        // 	const _this = this
        // 	_this.socketReceive(); // 在这里调用socketReceive方法
        // 	_this.socketStart = true;
        // 	callback && callback();
        // 	console.log('WebSocket连接已打开！');
        // });
        setTimeout(() => {
          _this.getHeartbeat();
        }, 2000);
      }
    } else {
      console.log("config/baseUrl socketUrl为空");
    }
  }
  //Socket给服务器发送消息
  send(data, callback) {
    const _this = this;
    // 将16进制字符串转换为字节数组
    const hexString = "aa aa aa aa aa aa";
    const byteArray = hexString
      .match(/.{1,2}/g)
      .map((byte) => parseInt(byte, 16));
    const data1 = new Uint8Array(byteArray);
    uni.sendSocketMessage({
      data: data1,
      success: () => {
        console.log(111);
        callback && callback(true);
      },
      fail: (err) => {
        console.log(err, 222);

        callback && callback(false);
      },
    });
  }
  //Socket接收服务器发送过来的消息
  socketReceive() {
    const _this = this;
    uni.onSocketMessage(function (res) {
      // console.log("APP:----》收到服务器内容:",res);
      let data = JSON.parse(res.data);
      //console.log('收到服务器内容：', data);
      _this.acceptMessage && _this.acceptMessage(data);
    });
  }
  //关闭Socket
  closeSocket() {
    const _this = this;
    uni.closeSocket();
    _this.socketStart = false;
  }
  //监听Socket关闭
  monitorSocketClose() {
    const _this = this;
    uni.onSocketClose(function (res) {
      console.log("WebSocket 已关闭！");
      _this.socketStart = false;
      setTimeout(function () {
        //_this.init();
      }, 3000);
    });
  }
  //监听Socket错误
  monitorSocketError() {
    const _this = this;
    uni.onSocketError(function (res) {
      _this.socketStart = false;
      console.log("WebSocket连接打开失败，请检查！");
    });
  }
  //心跳
  getHeartbeat() {
    const _this = this;
    console.log("发送心跳包！");
    this.send(
      {
        type: "心跳",
        userUid: store.state.userid,
      },
      (val) => {
        setTimeout(() => {
          if (val) {
            _this.getHeartbeat();
          } else {
            if (!_this.socketStart) {
              _this.init();
            }
          }
        }, 10000);
      }
    );
  }
}
const mySocket = new socket();
export default mySocket;
